import { Injectable } from '@angular/core';
import {Http, Response, URLSearchParams, RequestOptions, Headers} from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { HttpClient } from '@angular/common/http';
import { UtilsService } from '../utils/utils.service';
import { CookiesService } from './../cookies/cookies.service';

// import 'rxjs/add/operator/map';

@Injectable()
export class HttpRequestService {

  private utilsService = new UtilsService();
  private cookie = new CookiesService(document);
  constructor(public http: Http, public httpClient: HttpClient) { }


  /**
   * 基于HttpClient的GET请求
   * @param url, string, api url
   * @return Promise Object
   */
  public getRequest(url: string) {
    const header = {
      'Accept': 'application/json',
      'Content-Type': 'application/x-www-form-urlencoded',
      'user-name': this.cookie.getCookie('englishName') ? this.cookie.getCookie('englishName') : 'null'
    };
    // return this.http.get(url).map(res => res.json);
    return this.httpClient.get(url, {
      headers: header
    });
  }

  public postRequest(url: string, data: any) {
    const header = {
      'Accept': 'application/json',
      'Content-Type': 'application/x-www-form-urlencoded',
      'user-name': this.cookie.getCookie('englishName') ? this.cookie.getCookie('englishName') : null
    };
    return this.httpClient.post(url,
      this.utilsService.isObject(data) ? this.utilsService.encodeObject(data) : data,
      {
        headers: header
        // withCredentials: true //如果要携带Cookie，此处打开，且服务端也要设置Access-Control-Allow-Origin的域值且其值不能为*
      }
    );
  }

  public putRequest(url: string, data: any) {
    return this.httpClient.put(url, data);
  }
}